package com.liu.resume.ui.presenter;

import android.content.Context;
import android.util.Log;

import com.liu.resume.R;
import com.liu.resume.ui.contract.LoginContract;
import com.liu.resume.util.ToastUtil;
import com.liu.resume.viewmodel.UserOperateViewModel;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 类、方法注释 loginPresenterImpl实现类
 * @author creat  by:yts 2016/9/30
 * @author update by:
 *
 */
public class LoginPresenterImpl implements LoginContract.LoginPresenter, UserOperateViewModel.LoginObserver<String> {
    private UserOperateViewModel userOperateViewModel;
    private Context mContext;
    private LoginContract.LoginView mView;
    private Subscription subscription;
    private String mUserName;
    private String mPassWord;

    public LoginPresenterImpl(Context context, LoginContract.LoginView view) {
        mContext = context;
        mView = view;
        if (userOperateViewModel == null) {
            userOperateViewModel = new UserOperateViewModel(this);
        }
        view.setPresenter(this);
    }


    @Override
    public void subscribe(Observer observer) {
        //此处应该login
        subscription = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                //此处应该login
                userOperateViewModel.login(mUserName, mPassWord);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    public void unSubscribe() {
        subscription.unsubscribe();
    }

    public void start(String mUserName, String mPassWord) {
        this.mUserName = mUserName;
        this.mPassWord = mPassWord;
        mView.showProgress(mContext.getResources().getString(R.string.login));
        subscribe(this);
    }


    @Override
    public void onDestroy() {
        unSubscribe();
        mView = null;
    }

    @Override
    public void onCompleted() {
        Log.e("onCompleted","onCompleted");
//        dismissLoadingDialog();
       mView.onLoginSuccess();
    }

    @Override
    public void onError(Throwable e) {
        Log.e("onError","onError");
        mView.dismissProgress();
        ToastUtil.show(e.toString());
    }

    @Override
    public void onNext(String s) {
        Log.e("onNext","onNext");
        mView.dismissProgress();
        ToastUtil.show(s);
        // isLogin  notify view login
    }

}
